var bs = require("browser-sync");
var fs = require("fs");
var fm = require("front-matter");
var marked = require("marked");

var files = [
    "./*.html",
    "./demo/**/*.*",
    "./static/**/*.*"
]
bs.init(files, {
    server: {
        baseDir: "./"
    }
})
fs.watch("./markdown/", function(err, file) {
    if (file) {
        (function(file){
            buildHtml(file);
        })(file);
    }
})

function buildHtml(fileName) {
    console.log(fileName);
        var stat = fs.statSync('./markdown/' + fileName);
        if (stat.isDirectory()) {
            console.log(fileName + " is Dir");
        } else if (stat.isFile()) {
            var data = fs.readFileSync("./markdown/" + fileName, 'utf8')
            var md = fm(data);
            md.attributes.time = new Date(stat.atime).toLocaleDateString();
            md.body = md.body.replace(/\.\.\/static\//g, "./static/");
            fs.writeFileSync("./static/art/" + md.attributes.url, md.body, "utf8")
        }
        bs.reload();
}